/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {useBreakpointValue} from '@hadss/react_native_adaptive_layout';
import React, {forwardRef, useImperativeHandle, useState} from 'react';
import {
  View,
  Text,
  Image,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  FlatList,
  Platform,
  StatusBar,
  KeyboardAvoidingView,
} from 'react-native';
import {MessageItem} from './type.ts';

type ContMessageItem = {
  id: string;
  type: 'left' | 'right' | 'time';
  content: string;
  isSpecial?: boolean;
};

interface ChatScreenRef {
  show: () => void;
  hide: () => void;
  updateData: (newData: MessageItem) => void;
}

const ChatScreen = forwardRef((props: {activeItem: MessageItem}, ref: React.Ref<ChatScreenRef>) => {
  let {activeItem} = props;
  const messageData: ContMessageItem[] = [
    {
      id: '1',
      type: 'left',
      content: '',
      isSpecial: true,
    },
    {
      id: '2',
      type: 'left',
      content: '请你喝奶茶，快点单吧！速度速度，就差你了',
    },
    {
      id: '3',
      type: 'time',
      content: '10:28',
    },
    {
      id: '4',
      type: 'right',
      content: '哈哈，今天有什么喜事',
    },
  ];
  const currentBp = useBreakpointValue<string>({
    base: 'base',
    sm: 'sm',
    md: 'md',
    lg: 'lg',
    xl: 'xl',
  }) as string;

  const [isVisible, setIsVisible] = useState<boolean>(() => {
    return currentBp !== 'sm' && currentBp !== 'base';
  });
  const [showItem, setshowItem] = useState<MessageItem>({
    id: activeItem.id,
    name: activeItem.name,
    message: activeItem.message,
    time: activeItem.time,
    avatar: activeItem.avatar,
    unread: null,
  });
  useImperativeHandle(ref, () => {
    return {
      show: (): void => {
        // 显示详情页
        setIsVisible(true);
      },
      hide: (): void => {
        // 隐藏详情页
        setIsVisible(false);
      },
      updateData: (newData: MessageItem): void => {
        // 处理接收到的数据
        setshowItem(newData);
      },
    };
  });

  const renderItem = ({item}: {item: ContMessageItem}): JSX.Element | null => {
    if (item.type === 'time') {
      return <Text style={styles.time}>{item.content}</Text>;
    }

    if (item.type === 'left') {
      return (
        <View style={styles.leftItem}>
          <Image
            style={styles.avatar}
            source={require('../../../assets/images/touxiang.png')}
          />
          {item.isSpecial ? (
            <View style={styles.leftItemContent}>
              <Image source={require('../../../assets/images/naicha.png')} />
              <Text style={styles.tip}>芬芬邀请你喝奶茶啦！</Text>
              <Image
                source={require('../../../assets/images/naichaBJ.png')}
                style={{marginVertical: 8, width: '100%'}}
              />
              <Text style={styles.xcx}>小程序</Text>
            </View>
          ) : (
            <Text style={styles.leftItemContent}>{item.content}</Text>
          )}
        </View>
      );
    }

    if (item.type === 'right') {
      return (
        <View style={styles.rightItem}>
          <Text style={styles.rightItemContent}>{item.content}</Text>
          <Image
            style={styles.avatar}
            source={require('../../../assets/images/touxiang.png')}
          />
        </View>
      );
    }

    return null;
  };

  return isVisible ? (
    <KeyboardAvoidingView
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
      style={
        currentBp === 'sm' || currentBp === 'base'
          ? styles.keyboardBgSm
          : styles.keyboardBg
      }>
      <View
        style={
          currentBp === 'sm' || currentBp === 'base'
            ? styles.containerSm
            : styles.container
        }>
        <View style={styles.titleWrap}>
          <View style={styles.iconWrap}>
            <TouchableOpacity
              onPress={(event): void => {
                event.stopPropagation();
                if (
                  (ref as React.RefObject<ChatScreenRef>).current &&
                  (currentBp === 'sm' || currentBp === 'base')
                ) {
                  setIsVisible(false);
                }
              }}>
              <Image
                style={styles.titleImg}
                source={require('../../../assets/images/left.png')}
              />
            </TouchableOpacity>
            <Text style={styles.title}>{showItem.name}</Text>
          </View>
          <View style={styles.iconWrap}>
            <Image source={require('../../../assets/images/right.png')} />
          </View>
        </View>
        <FlatList
          data={messageData}
          renderItem={renderItem}
          keyExtractor={(item): string => item.id}
          contentContainerStyle={styles.content}
          style={styles.list}
        />
        <View style={styles.bottomWrap}>
          <TouchableOpacity>
            <Image
              style={[
                styles.bottomImg,
                {width: 19, height: 19, marginHorizontal: 18, marginTop: 6},
              ]}
              source={require('../../../assets/images/smail.png')}
            />
          </TouchableOpacity>
          <TextInput style={styles.input} />
          <TouchableOpacity>
            <Image
              style={[
                styles.bottomImg,
                {width: 19, height: 19, marginHorizontal: 18, marginTop: 6},
              ]}
              source={require('../../../assets/images/lt_add.png')}
            />
          </TouchableOpacity>
        </View>
      </View>
    </KeyboardAvoidingView>
  ) : null;
});

const styles = StyleSheet.create({
  keyboardBg: {
    flex: 1,
  },
  keyboardBgSm: {
    zIndex: 222,
    position: 'absolute',
    height: '100%',
    width: '100%',
  },
  container: {
    flex: 1,
    backgroundColor: 'rgb(241, 243, 245)',
    paddingTop: Platform.OS === 'ios' ? 44 : StatusBar.currentHeight,
  },
  containerSm: {
    backgroundColor: 'rgb(241, 243, 245)',
    paddingTop: Platform.OS === 'ios' ? 44 : StatusBar.currentHeight,
    zIndex: 223,
    position: 'absolute',
    height: '100%',
    width: '100%',
  },
  titleWrap: {
    height: 56,
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingHorizontal: 5,
    backgroundColor: 'rgb(241, 243, 245)',
  },
  title: {
    lineHeight: 56,
    color: 'rgba(0, 0, 0, 0.9)',
    fontSize: 26,
    fontWeight: '700',
  },
  titleImg: {
    marginRight: 8,
    width: 40,
    height: 40,
  },
  iconWrap: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  list: {
    flex: 1,
  },
  content: {
    paddingHorizontal: 23,
    paddingBottom: 20,
  },
  avatar: {
    width: 40,
    height: 40,
    borderRadius: 20,
  },
  leftItem: {
    flexDirection: 'row',
    justifyContent: 'flex-start',
    marginTop: 24,
    alignItems: 'flex-start',
  },
  tip: {
    color: 'rgb(24, 36, 49)',
    fontSize: 14,
    fontWeight: '400',
    lineHeight: 19,
  },
  xcx: {
    color: 'rgb(138, 144, 151)',
    fontSize: 10,
    fontWeight: '400',
    lineHeight: 13,
  },
  leftItemContent: {
    backgroundColor: 'rgb(255, 255, 255)',
    borderTopRightRadius: 20,
    borderBottomRightRadius: 20,
    borderBottomLeftRadius: 20,
    padding: 12,
    color: 'rgb(24, 36, 49)',
    fontSize: 14,
    fontWeight: '400',
    marginLeft: 12,
    maxWidth: '61.94%',
  },
  time: {
    textAlign: 'center',
    marginVertical: 12,
    color: 'rgb(24, 36, 49)',
    opacity: 0.6,
  },
  rightItem: {
    flexDirection: 'row',
    justifyContent: 'flex-end',
    alignItems: 'flex-end',
  },
  rightItemContent: {
    backgroundColor: 'rgb(10, 89, 247)',
    borderTopLeftRadius: 20,
    borderBottomRightRadius: 20,
    borderBottomLeftRadius: 20,
    padding: 12,
    color: 'rgb(255, 255, 255)',
    marginRight: 12,
    maxWidth: '61.94%',
    fontSize: 14,
    fontWeight: '400',
  },
  bottomWrap: {
    flexDirection: 'row',
    backgroundColor: 'rgb(241, 243, 245)',
    paddingVertical: 7,
    alignItems: 'flex-start',
    height: 76,
  },
  input: {
    flex: 1,
    height: 34,
    borderWidth: 0,
    borderRadius: 20,
    backgroundColor: 'white',
    paddingHorizontal: 15,
    paddingVertical: 0,
  },
  bottomImg: {
    resizeMode: 'contain',
  },
});

export default ChatScreen;
